import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * socket服务端负责转发客户端消息，开局洗牌确定先后手
 */
public class Server {
    static Socket p1;//玩家一
    static Socket p2;
    static SocketThread P1thread;//玩家一的线程
    static SocketThread P2thread;
    static int[] LibraryIndex = new int[28];

    /**
     * 主入口
     * @param args
     */
    public static void main(String[] args)  {
        try {
            scoketServer();
        }catch (Exception e){
            e.printStackTrace();
            System.exit(-1);
        }
    }
    /**
    *开启服务端，连接客户端
    */
    public static void scoketServer() throws IOException {

        ServerSocket server = new ServerSocket(8080);
        System.out.println("Server already wait for Client···");
        p1 = server.accept();
        System.out.println(p1.getInetAddress().getHostAddress()+"in");
        new SocketThread(p1).start();
        System.out.println("wait for Client···");
        p2 = server.accept();
        System.out.println(p1.getInetAddress().getHostAddress()+"in");
        new SocketThread(p2).start();
    }
    /**
     *将传入的数组转换为字符串，用于发送到各客户端确定牌的序列
     * @param array 牌序数组
     * @return 牌序字符串
     */
    public static String ArrayToString(int[] array){

        StringBuilder sb = new StringBuilder();
        for(int i = 0;i < array.length;i++){
            sb.append(array[i]);
            sb.append(" ");
        }
        return sb.toString();
    }

}

/**
 * 所有通道写入流的集合
 */
class SocketThread extends Thread {

    private static List<PrintWriter> list =new ArrayList<PrintWriter>();
    static boolean isShuffled = false;
    static boolean hasSend = false;
    static boolean hasJudgeWhoFirst = false;
    static int ClientNum = 0;
    static int PassCount = 0;

    private BufferedReader bufferedReader;
    private PrintWriter printWriter;
    public SocketThread(Socket socket) throws IOException {
        this.bufferedReader = new BufferedReader(new InputStreamReader(socket
                .getInputStream()));
        this.printWriter = new PrintWriter(socket.getOutputStream());
        list.add(printWriter);
    }
    /**
     *洗牌，将1~28打乱
     */
    public  int[] Shuffle(int[] LibraryIndex){

        for(int i = 0;i < 28;i++){
            LibraryIndex[i] = i;
        }
        Random r = new Random();
        for(int i = 0;i < LibraryIndex.length;i++) {
            int tmp;
            int x = r.nextInt(LibraryIndex.length);
            tmp = LibraryIndex[i];
            LibraryIndex[i] = LibraryIndex[x];
            LibraryIndex[x] = tmp;
        }
        return LibraryIndex;
    }
    @Override
    public void run() {
        String string = null;
        while (true) {
            try {
                // 服务器在通道中读到的信息回显给客服端
                string = bufferedReader.readLine();
                System.out.println(this.getName()+" Receive:"+string);
                OpJudge(string);
            } catch (IOException e) {
                System.out.println(e.getMessage());
                System.exit(-1);
            }
        }

    }
    /**
     *区分客户端传进来的命令
     */
    private  void OpJudge(String str){

        String[] msg = str.split(" ");
        switch (msg[0]){
            case "Ready":
                ClientNum++;
                if(ClientNum == 2){
                   ClientNum = 0;
                   sendToAll("Already");
                }
                break;
            case "Shuffle":
                System.out.println(this.getName()+" "+isShuffled);
                if(isShuffled){
                    isShuffled = false;
                    return;
                }else{
                    WhoFirst();
                    int[] index = Shuffle(Server.LibraryIndex);
                    String s = Server.ArrayToString(index);
                    hasSend = false;
                    sendToAll("LibraryIndex "+s);
                    isShuffled = true;
                }
                break;
            case "put":
                sendToOther(str);
                break;
            default:sendToOther(str);
        }
    }
    private  void WhoFirst(){
        if(hasJudgeWhoFirst){
            hasJudgeWhoFirst = false;
        }else{
            Random random = new Random();
            int a = random.nextInt();
            int b = random.nextInt();
            if(a > b) {
                sendToOther("First");
                sendMsg("Second");
            }else{
                sendToOther("Second");
                sendMsg("First");
            }
        }
    }
    private void sendToOther(String str){
        for(PrintWriter tempWriter:list ){
            if(!printWriter.equals(tempWriter)){
                System.out.println(getName()+"send to Other:"+str);
                tempWriter.write(str + "\r\n");
                tempWriter.flush();
            }
        }
    }
    private   void sendToAll(String str) {
        System.out.println("hs:"+hasSend);
        if (hasSend) {
            hasSend = false;
            return;
        }
        for (PrintWriter tempWriter : list) {
            tempWriter.write(str + "\r\n");
            tempWriter.flush();
        }
        hasSend = true;
    }
    public void sendMsg(String msg){
        printWriter.write(msg+"\r\n");
        printWriter.flush();
    }
}